package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IBlogService blogService;
    @Resource
    private IFollowService followService;
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public Result queryBlogById(Long id) {
        // 查询blog
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }

        blogUser(blog);
        if(blog.getName() == null) {
            return Result.fail("用户不存在");
        }
        blogLiked(blog);

        return Result.ok(blog);
    }

    public Blog blogUser(Blog blog) {
        //查询用户
        User user = userService.getById(blog.getUserId());
        if(user == null) {
            return blog;
        }
        // 返回笔记
        blog.setIcon(user.getIcon());
        blog.setName(user.getNickName());

        return blog;
    }

    public void blogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        // 如果用户未登录，则不需要查询是否点赞
        if(user == null) {
            return;
        }
        // 判断用户是否已经点赞
        String key = BLOG_LIKED + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());

        blog.setIsLiked(score != null);
    }
    
    
    @Override
    public Result likeBlog(Long id) {
        UserDTO user = UserHolder.getUser();
        // 判断用户是否已经点赞
        String key = BLOG_LIKED + id;
        Double score = stringRedisTemplate.opsForZSet().score(key, user.getId().toString());
        // 如果未点赞，可以点赞
        if(score==null) {
            // 点赞数量+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                // 保存用户到Redis的Set集合
                stringRedisTemplate.opsForZSet().add(key, user.getId().toString(),System.currentTimeMillis());
            }
            return Result.ok();
        }
        // 如果已点赞，取消点赞
        boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
        // 把用户从Redis的Set集合移除
        if(isSuccess) {
            stringRedisTemplate.opsForZSet().remove(key, user.getId().toString());
        }
        return Result.ok();
        
    }

    @Override
    public Result queryMyBlog(Integer current) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .eq("user_id", user.getId())
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        
        records.forEach(blog->{
            this.blogUser(blog);
            this.blogLiked(blog);
                });

        return Result.ok(records);
    }

    @Override
    public Result queryBlogLikes(Long id) {
        // 查询点赞的前5个用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().reverseRange(BLOG_LIKED + id, 0, 4);
        if(top5 == null || top5.isEmpty()) {
            return Result.ok(Collectors.toList());
        }
        // 将Set<String>转换为List<Long>
        List<Long> topList = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 查询顺序
        String queryList = StrUtil.join(",", topList);
        // 查询用户信息
        List<UserDTO> userList = userService.query().in("id",topList).last("order by field(id ,"+ queryList+")").list().stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        // 返回结果
        return Result.ok(userList);


    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean success = blogService.save(blog);
        // 将博文id推送给所有粉丝
        if(success){
            // 获取所有粉丝的id
            List<Long> ids = followService.lambdaQuery().eq(Follow::getFollowUserId, user.getId())
                    .list()
                    .stream()
                    .map(follow -> follow.getUserId())
                    .collect(Collectors.toList());
            // 将博文id推送给粉丝
            ids.forEach(id -> {
                String key = "feed:"+ id;
                // 将博文id推送到粉丝的Redis列表中
                stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
            });

        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 获取用户
        UserDTO userDTO = UserHolder.getUser();
        // 查询收件箱，获取滚动分页所需的数据
        String key = "feed:"+ userDTO.getId();
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        // 解析数据
        if(typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }

        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int nextOffset =1;

        for(ZSetOperations.TypedTuple<String> tuple:typedTuples){
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            if(time==minTime) {
                nextOffset++;
            } else {
                minTime = time;
                nextOffset = 1;
            }
        }
        // 根据笔记id查询笔记
        List<Blog> lists = blogMapper.listByIdsByOrder(ids);
        // 封装数据
        for(Blog blog : lists) {
            // 设置用户信息
            blogUser(blog);
            // 设置点赞状态
            blogLiked(blog);
        }

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(lists);
        scrollResult.setOffset(nextOffset);
        scrollResult.setMinTime(minTime);
        // 返回
        return Result.ok(scrollResult);
    }
}
